import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Statistic } from 'antd';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, PieChart, Pie, Cell } from 'recharts';
import { ArrowUpOutlined, UserOutlined, CalendarOutlined, CarOutlined, DollarOutlined } from '@ant-design/icons';
import { getOrders, getServices, getUsers, getChartData } from '../services/api';
import './Dashboard.css';

const Dashboard = () => {
  const [stats, setStats] = useState({
      totalUsers: 0,
      totalServices: 0,
      totalOrders: 0,
      totalRevenue: 0,
      usersGrowth: 0,
      servicesGrowth: 0,
      ordersGrowth: 0,
      revenueGrowth: 0
    });
  const [chartData, setChartData] = useState([]);
  const [orderStatusData, setOrderStatusData] = useState([]);
  const [serviceSalesData, setServiceSalesData] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        // 获取用户、服务和订单数据
        const users = await getUsers();
        const services = await getServices();
        const orders = await getOrders();
        const salesData = await getChartData();

        // 计算统计数据
        const totalUsers = users.length;
        const totalServices = services.length;
        const totalOrders = orders.length;
        const totalRevenue = orders.reduce((sum, order) => sum + order.amount, 0);

        // 模拟增长率 (实际应用中可能需要与上月数据比较)
        const usersGrowth = 15;
        const servicesGrowth = 8;
        const ordersGrowth = 20;
        const revenueGrowth = 25;

        // 订单状态分布
        const statusCounts = {
          completed: orders.filter(order => order.status === 'completed').length,
          pending: orders.filter(order => order.status === 'pending').length,
          cancelled: orders.filter(order => order.status === 'cancelled').length
        };

        const statusData = [
          { name: '已完成', value: statusCounts.completed },
          { name: '待处理', value: statusCounts.pending },
          { name: '已取消', value: statusCounts.cancelled }
        ];

        setStats({
          totalUsers,
          totalServices,
          totalOrders,
          totalRevenue,
          usersGrowth,
          servicesGrowth,
          ordersGrowth,
          revenueGrowth
        });

        setChartData(salesData);
        setOrderStatusData(statusData);

        // 模拟服务销售分布数据
        const serviceSales = services.map(service => ({
          name: service.serviceName || service.name,
          value: Math.floor(Math.random() * 100) + 10
        }));
        setServiceSalesData(serviceSales);
      } catch (error) {
        console.error('Error fetching dashboard data:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, []);

  const COLORS = ['#0088FE', '#00C49F', '#FFBB28'];

  return (
    <div className="dashboard-container">
      <h2 className="page-title">运营概览</h2>

      <Row gutter={[16, 16]} className="stats-row">
        <Col xs={24} sm={12} md={6} lg={6} xl={6}>
          <Card className="stat-card">
            <Statistic
              title="总客户数"
              value={stats.totalUsers}
              prefix={<UserOutlined />}
              suffix={
                <span className="growth-indicator positive">
                  <ArrowUpOutlined size={14} /> {stats.usersGrowth}%
                </span>
              }
            />
          </Card>
        </Col>

        <Col xs={24} sm={12} md={6} lg={6} xl={6}>
          <Card className="stat-card">
            <Statistic
              title="服务项目数"
              value={stats.totalServices}
              prefix={<CarOutlined />}
              suffix={
                <span className="growth-indicator positive">
                  <ArrowUpOutlined size={14} /> {stats.servicesGrowth}%
                </span>
              }
            />
          </Card>
        </Col>

        <Col xs={24} sm={12} md={6} lg={6} xl={6}>
          <Card className="stat-card">
            <Statistic
              title="总预约数"
              value={stats.totalOrders}
              prefix={<CalendarOutlined />}
              suffix={
                <span className="growth-indicator positive">
                  <ArrowUpOutlined size={14} /> {stats.ordersGrowth}%
                </span>
              }
            />
          </Card>
        </Col>

        <Col xs={24} sm={12} md={6} lg={6} xl={6}>
          <Card className="stat-card">
            <Statistic
                title="总营收"
                value={stats.totalRevenue}
                prefix={<DollarOutlined />}
                suffix={
                  <span className="growth-indicator positive">
                    <ArrowUpOutlined size={14} /> {stats.revenueGrowth}%
                  </span>
                }
                formatter={(value) => `¥ ${value.toLocaleString()}`}
              />
          </Card>
        </Col>
      </Row>

      <Row gutter={[16, 16]} className="charts-row">
          <Col xs={24} lg={12}>
          <Card title="营收趋势" className="chart-card">
            <ResponsiveContainer width="100%" height={400}>
              <BarChart
                data={chartData}
                margin={{ top: 20, right: 30, left: 20, bottom: 5 }}
              >
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="name" />
                <YAxis />
                <Tooltip />
                <Legend />
                <Bar dataKey="sales" name="服务收入" fill="#1890ff" />
                <Bar dataKey="profit" name="净利润" fill="#52c41a" />
              </BarChart>
            </ResponsiveContainer>
          </Card>
        </Col>
        <Col xs={24} lg={12}>
          <Card title="预约状态分布" className="chart-card">
            <ResponsiveContainer width="100%" height={400}>
              <PieChart>
                <Pie
                data={orderStatusData}
                cx="50%"
                cy="50%"
                labelLine={false}
                outerRadius={120}
                fill="#8884d8"
                dataKey="value"
                label={({ name, percent }) => `${name}: ${(percent * 100).toFixed(0)}%`}
              >
                {orderStatusData.map((entry, index) => (
                  <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                ))}
              </Pie>
                <Tooltip formatter={(value) => [`${value} 个`, '预约数']} />
              </PieChart>
            </ResponsiveContainer>
          </Card>
        </Col>
      </Row>

        <Row gutter={[16, 16]} className="charts-row">
          <Col xs={24}>
            <Card title="服务销售分布" className="chart-card">
              <ResponsiveContainer width="100%" height={400}>
                <PieChart>
                  <Pie
                    data={serviceSalesData}
                    cx="50%"
                    cy="50%"
                    labelLine={false}
                    outerRadius={120}
                    fill="#8884d8"
                    dataKey="value"
                    nameKey="name"
                    label={({ name, percent }) => `${name}: ${(percent * 100).toFixed(0)}%`}
                  >
                    {serviceSalesData.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                    ))}
                  </Pie>
                  <Tooltip formatter={(value) => [`${value} 次`, '服务次数']} />
                </PieChart>
              </ResponsiveContainer>
            </Card>
          </Col>
        </Row>

      </div>
  );
};

export default Dashboard;